<?php
namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\publics\Follow;
use app\common\model\publics\Likecoll;
use app\common\model\publics\Report;
use app\common\model\publics\Reportlog;
use app\common\model\publics\School;
use app\common\model\publics\Shop;
use app\common\model\publics\Helpcate;
use app\common\model\publics\Helplist;
use app\common\model\publics\Huati;
use app\common\model\shop\Goods;
use app\common\model\user\Message;
use app\common\model\user\Send;
use app\common\model\Trends;
use app\common\model\trends\Comment;
use app\common\model\Circle;
use app\common\model\circle\Apply;
use app\common\model\circle\Haowus;
use app\common\model\circle\Cate as CircleCate;
use app\common\model\circle\User as CircleUser;
use app\common\model\circle\Notice as CircleNotice;
use app\common\model\circle\Admin as CircleAdmin;
use app\common\model\Scenic;
use app\common\model\Category as CategoryModel;
use app\common\model\ShopCategory;
use app\common\model\Order as OrderModel;
use think\Config;
use think\Db;
/**
 * 个人中心
 */
class My extends Api
{
    //protected $noNeedLogin = ['help_detail','help','system_news','system_detail','edituser','join_circle','haowus_add','haowus_update','haowus_shoucang','haowus_list','get_category','association','associated_scenics'];
    protected $noNeedLogin = ['help_detail','help','system_news','system_detail','edituser','join_circle','getuserinfo','associated_scenics'];
    protected $noNeedRight = ['*'];

    /**
     * 个人信息
     * 
	 * @ApiMethod (POST)
	 * @param int $type 用户类型 （1我的个人信息，2别人的个人信息）
	 * @param int $user_id 用户id
     */
	public function getuserinfo() {
		$type = $this->request->post("type");//1我的个人信息，2别人的个人信息
		$user_id = $this->request->post("user_id");
		if($type == 1){
			$data = $this->auth->getUserinfo();
			$data['avatar'] = cdnurl($data['avatar'],true);
			//最新消息
			$send = Send::where(['user2_id'=>$this->auth->id,'is_see'=>2])->find();
			$send2 = Reportlog::where(['user_id'=>$this->auth->id,'is_see'=>2])->find();
			if($send || $send2){
				$data['is_see'] = 2;
			}else{
				$data['is_see'] = 1;
			}
			
			if ($data['school_id']) {
			   $schoolModel = new \app\common\model\School();
			   $school = $schoolModel->find($data['school_id']);  
			   $data['school_name'] = $school['school_name'];
			}
		}elseif($type == 2){
			$data = \app\common\model\User::get($user_id);
			if(empty($data)){
				$this->success("用户不存在",[],2);
			}
			if($this->auth->id == $user_id){//自己访问开锁
				$data->lock_coll = 1;
				$data->lock_dt = 1;
			}
			$data->append(['is_follow']);
			//$data->is_follow = Db::name("publics_follow")->where(['user2_id'=>$user_id,'user_id'=>$this->auth->id])->find()?1:2;
			$data->is_follow = Follow::where(['user2_id'=>$user_id,'user_id'=>$this->auth->id])->find()?1:2;
		}else{
			$this->error("参数错误");
		}
		$this->success("",$data);
	}

	/**
	 * 锁开关
     * 
	 * @ApiMethod (POST)
	 * @param int $type 锁类型（1动态锁 2收藏锁）
	 * @param int $is_lock 开关 （1开 2关）
	 */
	public function lock_open() {
		$user_id = $this->auth->id;
		$type = $this->request->post('type', 0);//1动态锁 2收藏锁
		$is_lock = $this->request->post('is_lock', 0);//1开2关

		if(empty($type) || empty($is_lock)){
			$this->success("参数错误",[],2);
		}

		$user = \app\common\model\User::get($user_id);

		if($type == 1){
			$res = $user->save(['lock_dt'=>$is_lock,'updatetime'=>time()]);
		}elseif ($type == 2){
			$res = $user->save(['lock_coll'=>$is_lock,'updatetime'=>time()]);
		}else{
			$this->success("参数错误",[],2);
		}

		if($res){
			$this->success("操作成功");
		}else{
			$this->error('出差了');
		}
	}

	/**
	 * 个人或别人的动态
     * 
	 * @ApiMethod (POST)
	 * @param int $type  类型
	 * @param int $user_id 用户id
	 * @param int $page 当前页码
	 * @param int $count 每页数量
	 */
	public function trends(){
		$type = $this->request->post('type', 0);
		$user_id = $this->request->post('user_id', 0);
		$page = $this->request->post('page', 1);
		$count = $this->request->post('count', 10);
		$is_self_top = $this->request->post('is_self_top', 0);
		$circles_id = Config::get("site2.ggqz");//公共圈子

		$where = [];
		$where['is_draft'] = 2;
		
		if($type == 1){
			$where['user_id'] = $this->auth->id;
			$user_id = $this->auth->id;
		}else{
			if(empty($user_id)){
				$this->error('参数错误');
			}
			$where['user_id'] = $user_id;
			$where['is_see'] = 1;
			if($this->auth->id != $user_id) {
				$where['cate_id'] = array('neq',1);
				$where['is_name'] = array('neq',1);
			}
		}
		//$list = \app\common\model\Trends::where($where)->order("id desc")->paginate($count, false, ["page" => $page]);
        $scenicModel = new Scenic();
		$query = Trends::where($where);
		if($is_self_top == 1){
		    $query->order('is_self_top', 'desc');
		}
		$list = $query->order("id desc")->paginate($count, false, ["page" => $page]);
		foreach ($list as $v){
			$v->append(['userinfo']);
			$v->userinfo = getuser($v,$user_id,$circles_id);
			if(!strpos($v->goods_id, ',')) {
				$scenics = $scenicModel->where(['id'=>$v->goods_id])->find();
				//print_r($scenics);
				$v->scenic_imags = $scenics['scenic_images'];
				$v->scenic_address = $scenics['address'];
			}
		}
		$this->success("", $list);
	}

	/**
	 * 我的草稿
     * 
	 * @ApiMethod (POST)
	 * @param int $page 当前页码
	 * @param int $count 每页数量
	 */
	public function trends_draft(){
		$user_id = $this->auth->id;
		$page = $this->request->post('page', 1);
		$count = $this->request->post('count', 10);
		$circles_id = Config::get("site2.ggqz");//公共圈子
		$where = [];
		$where['user_id'] = $user_id;
		$where['is_draft'] = 1;
		$list = Trends::where($where)->order("id desc")->paginate($count, false, ["page" => $page]);
		//$list = \app\common\model\Trends::where($where)->order("id desc")->paginate($count, false, ["page" => $page]);
		foreach ($list as $v){
			$v->append(['userinfo']);
			$v->userinfo = getuser($v,$user_id,$circles_id);
		}
		$this->success("", $list);
	}

	/**
	 * 收藏列表
     * 
	 * @ApiMethod (POST)
	 * @param int $type  类型
	 * @param int $user_id 用户id
	 * @param int $page 当前页码
	 * @param int $count 每页数量
	 */
	public function coll(){
		$type = $this->request->post('type',1);
		$user_id = $this->request->post('user_id',0);
		$page = $this->request->post('page', 1);
		$count = $this->request->post('count', 10);
		$circles_id = Config::get("site2.ggqz");//公共圈子
		$where = [];
		$where['likecoll.type'] = 2;
		if($type == 1){
			$where['likecoll.user_id']=$this->auth->id;

		}else{
			if(empty($user_id)){
				$this->error('参数错误');
			}
			$where['likecoll.user_id']=$user_id;
		}

        $scenicModel = new Scenic();
		$list = Likecoll::with(['trends'])
		                ->where($where)
		                ->order("likecoll.id desc")
		                ->paginate($count, false, ["page" => $page]);
		foreach ($list as $row) {
			$row->visible(['id','type','trends_id']);
			$row->visible(['trends']);
			$row->trends->append(['userinfo']);
			$row->trends->userinfo = getuser($row->trends,$this->auth->id,$circles_id);
			if(!strpos($row->trends->goods_id, ',')) {
				$scenics = $scenicModel->where(['id'=>$row->trends->goods_id])->find();
				$row->trends->append(['scenic_imags']);
				$row->trends->scenic_imags = $scenics['scenic_images'];
				$row->trends->append(['scenic_address']);
				$row->trends->scenic_address = $scenics['address'];
			}
		}
		$this->success('请求成功',$list);
	}

	/**
	 * 关注、粉丝列表
     * 
	 * @ApiMethod (POST)
	 * @param int $type  类型 （1我的关注，2我的粉丝）
	 * @param int $page 当前页码
	 * @param int $count 每页数量
	 */
	public function gz_fs() {
		$user_id = $this->auth->id;
		$type = $this->request->post('type',0);//1我的关注，2我的粉丝
		$page = $this->request->post('page', 1);
		$count = $this->request->post('count', 10);
		$where = [];
		if($type == 1){
			$where["user_id"] =  $user_id;
		}elseif ($type == 2){
			$where["user2_id"] =  $user_id;
		}else{
			$this->error("参数错误");
		}
		$list = Follow::where($where)->order("id desc")->paginate($count, false, ["page" => $page]);
		foreach ($list as $v){
			$v->append(["number","nickname","avatar","fans","is_follow"]);
			if($type == 1){//我的关注
				$user = Db::name("user")->where(["id"=>$v->user2_id])->find();
				$v->number = $user['number'];
				$v->nickname = $user['nickname'];
				$v->avatar =  cdnurl($user['avatar'],true);
				$v->fans = $user['fans'];
			}elseif ($type == 2){//我的粉丝
				$user = Db::name("user")->where(["id"=>$v->user_id])->find();
				$v->number = $user['number'];
				$v->nickname = $user['nickname'];
				$v->avatar =  cdnurl($user['avatar'],true);
				$v->fans = $user['fans'];
			}
			$v->is_follow = $v->info($v,$type);
		}
		$this->success('请求成功',$list);
	}

	/**
	 * 删除动态
     * 
	 * @ApiMethod (POST)
	 * @param int $trends_id  动态id
	 */
	public function del_trends(){
		$user_id = $this->auth->id;
		$trends_id = $this->request->post('trends_id');
		$_type = $this->request->post('_type');
		$detail = Trends::where(['id' =>$trends_id, 'user_id' =>$user_id])->find();
		if(!$detail){
			$this->success("动态不存在",[],2);
		}
		if($_type == 'settopup'){
		    if($detail->is_self_top == 0){
		       	Trends::where(['user_id' =>$user_id])->update(['is_self_top' => 0]); 
		    }
	        $res = $detail->save(['is_self_top'=>$detail->is_self_top == 1?0:1]);
	    	$this->success('操作成功'); 
		} else {
    		$res = $detail->save(['deletetime'=>time()]);
    		$this->success('删除成功');
    		    
		}
	}

	/**
	 * 帮助中心
	 * @ApiMethod (POST)
	 */
	public function help(){
		$list = Helpcate::order('weigh desc')->select();
		foreach ($list as $k => $v){
			$list[$k]['list'] = Helplist::where(['helpcate_id'=>$v['id']])->field("id as help_id,title")->select();
		}
		$this->success('请求成功',$list);
	}

	/**
	 * 帮助详情
     * 
	 * @ApiMethod (POST)
	 * @param int $help_id  帮助信息id
	 */
	public function help_detail(){
		$help_id = $this->request->post('help_id');
		$detail = Helplist::where(['id'=>$help_id])->find();
		$this->success('请求成功',$detail);
	}

	/**
	 * 修改个人信息
     * 
	 * @ApiMethod (POST)
	 * @param string|array $params  个人信息数组
	 */
	public function edituser()
	{
	    if(!$this->auth->isLogin()) {
	        $this->error("请登录后操作");
	    }
		$user_id = $this->auth->id;
		$params = $this->request->post();
		$params['update_time'] = time();
		if(isset($params['school_id']) && $params['school_id'] == "null "){
			unset($params['school_id']);
		}
		$user = \app\common\model\User::get($user_id);
		$res = $user->save($params);
		if ($res) {
			$this->success('成功');
		} else {
			$this->error("失败");
		}
	}

	/**
	 * 学校列表
     * 
	 * @ApiMethod (POST)
	 * @param string $name  学校名称
	 * @param int $page     当前页码
	 * @param int $count    每页数量
	 */
	public function school(){
		$name = $this->request->post('name',"");
		$page = $this->request->post('page', 1);
		$count = $this->request->post('count', 10);
		$where = [];
		if($name){
			$where['name'] = array('like',"%$name%");
		}
		$list = School::where($where)
		              ->order("createtime desc")
		              ->paginate($count, false, ["page" => $page]);
		$this->success('成功',$list);
	}

	/**
	 * 添加学校
     * 
	 * @ApiMethod (POST)
	 * @param string $name  学校名称
	 */
	public function add_school(){
		$user_id = $this->auth->id;
		$name = $this->request->post('name',"");
		if(empty($name)){
			$this->success('请输入学校名称',[],2);
		}
		$school = School::where(['name'=>$name])->find();
		if($school){
			$this->success('学校已存在',[],2);
		}
		$res = School::create(['user_id'=>$user_id,'name'=>$name,'createtime'=>time()]);
		if($res){
			$this->success('成功');
		}else{
			$this->error('出差了');
		}
	}

	/**
	 * 店铺入驻
     * 
	 * @ApiMethod (POST)
	 * @param int $id  动态id
	 * @param string|array $param  店铺信息数组
	 */
	public function add_shop(){
		$param = $this->request->param();
		$id = $this->request->post('id', 0);
		$this->rule = [
			"shop_name|店铺名称"   => ["require"],
			"shop_type|店铺类型"   => ["require"],
			"state_times|营业时间" => ["require"],
			"area|省市区"          => ["require"],
			"address|详细地址"     => ["require"],
			"mobile|联系电话"      => ["require"],
			"image|门脸照片"       => ["require"],
			"fddbr_image|法人照片" => ["require"]
		];
		$this->checks($param);
		//$id = 18;//test
		if($id > 0){
			$trends = Shop::get($id);
			if(!$trends){
				$this->success('信息不存在',[],2);
			}
			$param['status'] = 1;
			$res = $trends->save($param);
		}else{
			$param['user_id'] = $this->auth->id;
			$res = Shop::create($param, true);
		}

		if ($res) {
			$this->success('提交成功');
		} else {
			$this->error("出差了");
		}
	}

	/**
	 * 留言
     * 
	 * @ApiMethod (POST)
	 * @param int $user_id    用户id
	 * @param int $message_id 信息id
	 * @param int $content    留言内容
	 */
	public function add_message(){
		$user_id = $this->auth->id;
		$user2_id = $this->request->post('user_id', 0);
		$message_id = $this->request->post('message_id', 0);
		$content = $this->request->post('content', '');

		if(!$user2_id){
			$this->success('参数错误',[],2);
		}
		if(!$content){
			$this->success('请输入留言内容',[],2);
		}
		$res = Message::create(['user_id'=>$user_id,'user2_id'=>$user2_id,'message_id'=>$message_id,'content'=>$content,'create_time'=>time()]);
		if ($res) {
            //添加记录
			send($user_id,$user2_id,3,$res->id);
			$this->success('提交成功');
		} else {
			$this->error("出差了");
		}
	}

	/**
	 * 留言列表
     * 
	 * @ApiMethod (POST)
	 * @param int $message_id  留言id
	 */
	public function message(){
		$user_id = $this->auth->id;
		$message_id = $this->request->post('message_id',0);
		$where = [];
		$where['user2_id'] = $user_id;
		$where['message_id'] = $message_id;
		$list = Message::where($where)
		               ->order("create_time desc")
			           ->limit(15)
		               ->select();
		foreach ($list as $row) {
			$row->append(['comment']);
			$row->comment = Message::where(['id'=>$row->message_id])->find();
		}
		$this->success("成功",$list);
	}

	/**
	 * 消息
     * 
	 * @ApiMethod (POST)
	 * @param int $type  类型
	 */
	public function news_index(){
		$user_id = $this->auth->id;
		$type = $this->request->post('type');
		if($type != 4){
			$data = Send::where(['user2_id'=>$user_id,'type'=>$type])->order('id desc')->find();
		}else{
			$data = Reportlog::where(['user_id'=>$user_id])->order('id desc')->find();
		}
		$this->success("成功",$data);
	}

	/**
	 * 点赞消息列表
	 * @ApiMethod (POST)
	 * @param int $page     当前页码
	 * @param int $count    每页数量
	 */
	public function like_news(){
		$user_id = $this->auth->id;
		$page = $this->request->post('page', 1);
		$count = $this->request->post('count', 10);
		$list = Likecoll::where(['type'=>array('in','1,3,4'),'user2_id'=>$user_id])
		                ->order('id desc')
		                ->paginate($count, false, ["page" => $page]);
		foreach ($list as $v){
			$v->append(['trend','comment']);
			$v->trend = $v->trends_id ? Trends::withTrashed()->where(['id'=>$v->trends_id])->find():[];
			$v->comment = $v->comment_id ? Comment::withTrashed()->where(['id'=>$v->comment_id])->find():[];
		}

		if($list){
			//已读操作
			$send = Send::where(['user2_id'=>$user_id,'type'=>1,'is_see'=>2])->select();
			foreach ($send as $v2){
				$v2->save(['is_see'=>1]);
			}
			$this->success("成功",$list);
		}else{
			$this->success("无数据",[]);
		}
	}

	/**
     * 评论消息列表
	 * @ApiMethod (POST)
	 * @param int $page     当前页码
	 * @param int $count    每页数量
     */
	public function comment_news(){
		$user_id = $this->auth->id;
		$page = $this->request->post('page', 1);
		$count = $this->request->post('count', 10);
		$list = Comment::where(['user2_id'=>$user_id])
		               ->order('id desc')
			           ->paginate($count, false, ["page" => $page]);
		foreach ($list as $v){
			$v->append(['trends','goods','comment']);
			$v->trends = $v->type==1?Trends::withTrashed()->where(['id'=>$v->trends_id])->find():[];
			$v->goods = $v->type==2?Goods::withTrashed()->where(['id'=>$v->trends_id])->find():[];
			$v->comment = $v->parent_id?Comment::get($v->parent_id):[];
		}

		if($list){
			//已读操作
			$send = Send::where(['user2_id'=>$user_id,'type'=>2,'is_see'=>2])->select();
			foreach ($send as $v2){
				$v2->save(['is_see'=>1]);
			}
			$this->success("成功",$list);
		}else{
			$this->success("无数据",[]);
		}
	}

	/**
	 * 留言消息
	 * @ApiMethod (POST)
	 * @param int $page     当前页码
	 * @param int $count    每页数量
	 */
	public function message_news(){
		$user_id = $this->auth->id;
		$page = $this->request->post('page', 1);
		$count = $this->request->post('count', 10);

		$list = Message::where(['user2_id'=>$user_id])
		               ->order('id desc')
			           ->paginate($count, false, ["page" => $page]);
		foreach ($list as $v){
			$v->append(['comment']);
			$v->comment = $v->message_id?Message::get($v->message_id):[];
		}

		if($list){
			//已读操作
			$send = Send::where(['user2_id'=>$user_id,'type'=>3,'is_see'=>2])->select();
			foreach ($send as $v2){
				$v2->save(['is_see'=>1]);
			}
			$this->success("成功",$list);
		}else{
			$this->success("无数据",[]);
		}
	}

	/**
	 * 举报消息
	 * @ApiMethod (POST)
	 * @param int $page     当前页码
	 * @param int $count    每页数量
	 */
	public function report_news(){
		//$this->auth->direct(4);
		$user_id = $this->auth->id;
		$page = $this->request->post('page', 1);
		$count = $this->request->post('count', 10);
		$list = Reportlog::with(['report'])
		                 ->where(['reportlog.user_id'=>$user_id])
		                 ->order('id desc')
			             ->paginate($count, false, ["page" => $page]);

		foreach ($list as $v){
			if($v->is_see == 2){
				$v->save(['is_see'=>1,'updatetime'=>time()]);
			}
			$v->append(['trends']);
			$v->trends = Trends::get($v->report->trends_id);
			//$v->trends_id = $v->report->trends_id;
		}

		if($list){

			$this->success("成功",$list);
		}else{
			$this->success("无数据",[]);
		}
	}

	/**
	 * 我要申诉
	 * @ApiMethod (POST)
	 * @param int $report_id    信息id
	 * @param string $describe  申诉描述
	 * @param string $images    申诉图片
	 */
	public function report_ss(){
		$user_id = $this->auth->id;
		$report_id = $this->request->post('report_id');
		$describe = $this->request->post('describe');
		$images = $this->request->post('images');

		if(!$describe){
			$this->success("请输入申诉内容",[],2);
		}

		$report = Report::where(['jb_user_id'=>$user_id,'id'=>$report_id])->find();
		if(!$report){
			$this->success("信息不存在",[],2);
		}
		if($report->ss_state > 0){
			$this->success("已申诉过 不可重复申诉",[],2);
		}

		$res = $report->save(['ss_state'=>1,'state'=>2,'ss_describe'=>$describe,'ss_images'=>$images,'ss_time'=>time()]);
		if($res){
			$this->success("申诉信息提交成功");
		}else{
			$this->error("出差了");
		}
	}

	/**
	 * 系统消息
	 * @ApiMethod (POST)
	 * @param int $page     当前页码
	 * @param int $count    每页数量
	 */
	public function system_news(){
		$user_id = $this->auth->id;
		$page = $this->request->post('page', 1);
		$count = $this->request->post('count', 10);
		$where = [];
		$where['type'] = 5;
		$where['user2_id'] = $user_id;
		$list = Send::where($where)->order("create_time desc")->paginate($count, false, ["page" => $page]);
		$this->success('成功',$list);
	}

	/**
	 * 系统消息
	 * @ApiMethod (POST)
	 * @param int $news_state 消息状态
	 * @param int $news_id    消息id
	 */
	public function system_detail(){
		$user_id = $this->auth->id;
		$news_state = $this->request->post('news_state', 0);
		$news_id = $this->request->post('news_id', 0);
		$data = [];
		if($news_state == 1){//公告驳回
			$notice = CircleNotice::where(['id'=>$news_id])->find();
			$data['title'] = '公告驳回';
			$data['createtime'] = date("Y-m-d H:i",$notice['createtime']);
			$data['content'] = $notice['content'];
			$data['apply_time'] = date("Y-m-d H:i",$notice['apply_time']);
			$data['yuanyin'] = $notice['memo'];
			$data['circle_id'] = $notice['circle_id'];
		}elseif ($news_state == 2){//吧主申请驳回
			$admin = CircleAdmin::where(['id'=>$news_id])->find();
            $circle = Circle::get($admin['circle_id']);
			$data['title'] = '吧主申请驳回';
			$data['createtime'] = date("Y-m-d H:i",$admin['createtime']);
			$data['circle_name'] = $circle->name;
			//原吧主头像，昵称
			$circleuser = CircleUser::where(['circle_id'=>$admin['circle_id'],'identity'=>1])->order('role desc')->find();
            $user = Db::name('user')->where(['id'=>$circleuser->user_id])->find();
			$data['y_avatar'] = cdnurl($user['avatar'],true);
			$data['y_nickname'] = $user['nickname'];
			//新吧主头像，昵称
			$user = Db::name('user')->where(['id'=>$admin['user_id']])->find();
			$data['x_avatar'] = cdnurl($user['avatar'],true);
			$data['x_nickname'] = $user['nickname'];
			$data['apply_time'] = date("Y-m-d H:i",$admin['apply_time']);
			$data['yuanyin'] = $admin['yuanyin'];
			$data['circle_id'] = $admin['circle_id'];
		}elseif ($news_state == 3){//管理员驳回
			$admin = CircleAdmin::where(['id'=>$news_id])->find();
			$circle = Circle::get($admin['circle_id']);
			$data['title'] = '管理员申请驳回';
			$data['createtime'] = date("Y-m-d H:i",$admin['createtime']);
			$data['circle_name'] = $circle->name;
			$data['apply_time'] = date("Y-m-d H:i",$admin['apply_time']);
		}elseif ($news_state == 4){//圈子申请驳回
			$circle = Circle::get($news_id);
			$data['title'] = '圈子申请驳回';
			$data['logo'] = cdnurl($circle->logo_image,true);
			$data['circle_name'] = $circle->name;
			$data['circle_cate'] = CircleCate::where(['id'=>$circle->circlecate_id])->value('name');
			$data['createtime'] = date("Y-m-d H:i",$circle->createtime);
			$data['apply_time'] = date("Y-m-d H:i",$circle->apply_time);
			$data['sq_yuanyin'] = $circle->yuanyin;
			$data['yuanyin'] = $circle->bh_yuanyin;
		}else{
			$this->success("参数错误",[],2);
		}
		$this->success('成功',$data);
	}

	/**
     * 加入圈子
	 * @ApiMethod (POST)
	 * @param int $circle_id 圈子id
     */
	public function join_circle(){
		$user_id = $this->auth->id;
		$circle_id = $this->request->post('circle_id', 0);
		$circle = Circle::get($circle_id);
		if(!$circle){
			$this->success('圈子不存在',[],2);
		}
		$circle_user = CircleUser::where(['user_id'=>$user_id,'circle_id'=>$circle_id])->find();
		if($circle_user){
			if($circle_user->is_auth == 2){
				$this->success('你已被拉黑无法加入圈子',[],2);
			}
			$this->success('你已加入圈子 无需重复加入');
		}

		//判断是否已经加入圈子
		$joinFlag = false;
		$circle_users = \app\common\model\circle\User::where(['user_id'=>$user_id])->select();
		foreach ($circle_users as $v){
		   if($v->circle_id > 1)  $joinFlag = true;
		}
		if($joinFlag) {
		    $this->error("六个月内最多只能加入一个圈子");
		}else {
		    $res = CircleUser::insert(['user_id'=>$user_id,'circle_id'=>$circle_id,'createtime'=>time()]);
    		if($res){
    			//初次加入圈子
    			exps($circle_id,$user_id,1);
    			$this->success('加入成功');
    		}else{
    			$this->error('出差了');
    		}
		}
	}

	/**
	 * 退圈
	 * @ApiMethod (POST)
	 * @param int $circle_id 圈子id
	 */
	public function refund_circle(){
		$user_id = $this->auth->id;
		$circle_id = $this->request->post('circle_id', 0);
		$where = [];
		$where['circle_id'] = $circle_id;
		$where['user_id'] = $user_id;

		$circle = CircleUser::where($where)->find();
		if(!$circle){
			$this->success("还未加入该圈子", [],2);
		}
		$res = $circle->delete();
		if($res){
			$this->success("退出成功");
		}else{
			$this->error('出差了');
		}
	}

	/**
     * 圈友管理层
	 * @ApiMethod (POST)
	 * @param int $circle_id 圈子id
    */
	public function CircleAdmin(){
		$user_id = $this->auth->id;
		$circle_id = $this->request->post('circle_id', 0);
		$data = [];
		//吧主
		//$data['list1'] = \app\common\model\circle\User::where(['circle_id' => $circle_id,'identity'=>1,'is_auth'=>1,'is_ban'=>2])->select();
		$list = CircleUser::where(['circle_id' => $circle_id,'identity'=>1,'role'=>2])->select();
		if($list){
			$data['list1'] = $list;
		}else{
			$data['list1'] = CircleUser::where(['circle_id' => $circle_id,'identity'=>1,'role'=>1])->select();
		}
		//管理员
		$data['list2'] = CircleUser::where(['circle_id' => $circle_id,'identity'=>2,'is_auth'=>1,'is_ban'=>2])->select();
		$this->success("", $data);
	}

	/**
     * 申请加入圈子
	 * @ApiMethod (POST)
	 * @param int $circle_id 圈子id
     */
	public function lairage(){
		$user_id = $this->auth->id;
		$circle_id = $this->request->post('circle_id', 0);
		$liyou = $this->request->post('liyou', '');
		$image = $this->request->post('image', '');
		$circle = Circle::get($circle_id);
		if(!$circle){
			$this->success('圈子不存在',[],2);
		}
		if(!$liyou){
			$this->success('请输入理由',[],2);
		}
		$circle_user = CircleUser::where(['user_id'=>$user_id,'circle_id'=>$circle_id])->find();
		if($circle_user){
			if($circle_user->is_auth == 2){
				$this->success('你已被拉黑无法加入圈子',[],2);
			}
			$this->success('你已加入圈子 无需重复加入...',[],2);
		}
		$apply = Apply::where(['user_id'=>$user_id,'circle_id'=>$circle_id,'state'=>1])->find();
		if($apply){
			$this->success('申请已提交 无需重新申请...',[],2);
		}

		$res = Apply::insert(['user_id'=>$user_id,'circle_id'=>$circle_id,'liyou'=>$liyou,'image'=>$image,'state'=>1,'createtime'=>time()]);
		if($res){
			$this->success('申请提交成功');
		}else{
			$this->error('出差了');
		}
	}

	/**
	 * 申请管理员
	 * @ApiMethod (POST)
	 * @param int $circle_id 圈子id
	 */
	public function apply_admin(){
		$user_id = $this->auth->id;
		$circle_id = $this->request->post('circle_id', 0);
		$circle = Circle::get($circle_id);
		if(!$circle){
			$this->success('圈子不存在',[],2);
		}

		$apply = CircleAdmin::where(['user_id'=>$user_id,'circle_id'=>$circle_id,'status'=>1])->find();
		if($apply){
			$this->success('申请已提交 无需重新申请...',[],2);
		}

		$res = CircleAdmin::insert(['user_id'=>$user_id,'type'=>2,'circle_id'=>$circle_id,'status'=>1,'createtime'=>time()]);
		if($res){
			$this->success('申请提交成功');
		}else{
			$this->error('出差了');
		}
	}

	/**
	 * 圈子管理员删除动态
	 * @ApiMethod (POST)
	 * @param int $trends_id 动态id
	 */
	public function admin_del_trends(){
		$trends_id = $this->request->post('trends_id');
		$detail = \app\common\model\Trends::where(['id' =>$trends_id])->find();
		if(!$detail){
			$this->success("动态不存在",[],2);
		}
		$res = $detail->save(['deletetime'=>time()]);
		$this->success('删除成功');
	}

	/**
	 * 圈子管理员审核动态
	 * @ApiMethod (POST)
	 * @param int $trends_id 动态id
	 * @param int $state     状态: 1=正常,2=封禁,3=已驳回,4=审核中
	 * @param int $is_see    谁可见: 1=公开,2=自己可见
	 * @param int $is_draft  草稿: 1=是,2=否
 	 * @param int $is_t_recommend  是否推荐到推荐页: 1=未设置,2=推荐,3=不推荐
	 * @param int $_cat     操作类型: audit=审核,recommend=推荐,see=自己可见
	 */
	public function admin_audit_trends(){
		$trends_id = $this->request->post('trends_id');
		$state = $this->request->post('state');
		$is_see = $this->request->post('is_see');
		$is_draft = $this->request->post('is_draft');
		$is_t_recommend = $this->request->post('is_t_recommend');
		$_index = $this->request->post('_index');
		$_cat = $this->request->post('_cat');
		$detail = Trends::where(['id' =>$trends_id])->find();
		if(!$detail){
			$this->success("动态不存在",[],2);
		}
		/*if($detail->state == 1) {
			$this->error('无需重复审核');
		}else {
			$res = $detail->save(['state'=>$state, 'is_see'=>$is_see]);
			$this->success('动态审核成功');
		}*/
		/*if($is_see == 2){
            $res = $detail->save(['state'=>$state, 'is_see'=>$is_see, 'is_draft'=>$is_draft]);
            $this->success('置草稿箱设置成功');
        }else {
            $res = $detail->save(['state'=>$state, 'is_see'=>$is_see, 'is_draft'=>$is_draft]);
            $this->success('动态审核成功');
        }*/
        $forms = [];
        switch($_cat){
            case 'audit':
                $forms = ['state'=>$state, 'is_see'=>$is_see, 'is_draft'=>$is_draft];
                if($_index == 2){ //通过并推荐
                    $forms['is_t_recommend'] = $is_t_recommend;
                }
                break;
             case 'recommend':
                $forms = ['is_t_recommend'=>$is_t_recommend];
                break;
             case 'see':
                $forms = ['is_see'=>$is_see];
                break;
        }
    	$res = $detail->save($forms);
    	$this->success('操作成功');
	}

	//上级评论循环减少回复数量
	private function circulate($parent_id)
	{
		$comment = Comment::get($parent_id);
		if ($comment) {
			$comment->setInc('num', -1);
			if ($comment->parent_id) {
				$this->circulate($comment->parent_id);
			}
		}
		return true;
	}

	/**
	 * 用户删除留言
	 * 
	 * @ApiMethod (POST)
	 * @param int $comment_id 留言id
	 */
	public function user_del_trends_comment(){
		$comment_id = $this->request->post('comment_id');
		$_type = $this->request->post('_type');
		$detail = Comment::where(['id' =>$comment_id])->find();
		if(!$detail){
			$this->success("留言不存在",[],2);
		}
		if($_type == 'settopup'){
		    $res = $detail->save(['is_top'=>$detail->is_top == 1?0:1]);
		    	$this->success('操作成功'); 
		} else {
		   	$parent_id = $detail->parent_id;//上层评论id
    		$res = $detail->save(['deletetime'=>time()]);
    		//留言删除后，动态中comment -1
    		$trendId = $detail->trends_id;
    		$trendDetail = Trends::where(['id' =>$trendId])->find();
    		if($trendDetail) {
    			$trendDetail->setInc('comment', -1);
    			//给话题减少评论数
    			$list = \app\common\model\trends\Huati::where(['trends_id' => $trendId])->select();
    			foreach ($list as $k => $v) {
    				$huati = Huati::get($v->huati_id);
    				if ($huati) {
    					$huati->setInc('comment', -1);
    				}
    			}
    			//上层评论num循环-1
    			if ($parent_id) {
    				$this->circulate($parent_id);
    			}
    		}
    		$this->success('删除成功'); 
		}
	
	}
	
	/**
	 * 好物收藏
	 * 
	 * @ApiMethod (POST)
     * @param int user_id 用户id
	 * @param int scenic_id 景区id
	 */
	public function haowus_shoucang(){
		$scenic_id = $this->request->post('scenic_id');
		$user_id = $this->request->post('user_id');
		//$user_id = $this->auth->id;
		if(empty($scenic_id) || empty($user_id)){
			$this->success("参数错误",[],2);
		}
		$result = \app\common\model\User::where('id', $user_id)->update(['collect_scenic_id'=>$scenic_id]);
		if($result) {
			$this->success(__('收藏成功'));
		}else {
			$this->error("收藏失败");
		}
	}

	/**
	 * 好物添加
	 * 
	 * @ApiMethod (POST)
	 * @param string scenic_ids 景区ids
     * @param int user_id 用户id
	 */
	public function haowus_add(){
		$scenic_ids = $this->request->post('scenic_ids');
		$user_id = $this->request->post('user_id');
		//$user_id = $this->auth->id;
		if(empty($scenic_ids) || empty($user_id)){
			$this->success("参数错误",[],2);
		}
		foreach(explode(',', $scenic_ids) as $scenicId) {
			$HaowusDetail = Haowus::where(['user_id'=>$user_id, 'scenic_id'=>$scenicId])->find();
			if(!$HaowusDetail) {
				Haowus::insert(['user_id'=>$user_id, 'scenic_id'=>$scenicId, 'create_time'=>time()]);
			}else if($HaowusDetail['delete_time'] != null){
				Haowus::where(['user_id'=>$user_id, 'scenic_id'=>$scenicId])->update(['is_top'=>0, 'delete_time'=>null]);
			}
		}
		$this->success('添加成功');
	}
	
	/**
	 * 好物置顶 删除
	 * 
	 * @ApiMethod (POST)
	 * @param string ids   好物主键 ids
     * @param int user_id 用户id
     * @param int type    类型 1=删除  2=置顶修改
	 */
	public function haowus_update(){
		$haowu_ids = $this->request->post('ids');
		$user_id = $this->request->post('user_id');
		//$user_id = $this->auth->id;
		$type = $this->request->post('type');
		if(empty($haowu_ids) || empty($user_id) || empty($type)){
			$this->success("参数错误",[],3);
		}
		if($type == 1) { //删除
			foreach(explode(',', $haowu_ids) as $haowu_id) {
				$HaowusDetail = Haowus::where(['user_id'=>$user_id, 'id'=>$haowu_id])->find();
				if($HaowusDetail) {
					Haowus::where(['user_id'=>$user_id, 'id'=>$haowu_id])->update(['delete_time'=>time()]);
				}
			}
		} else if($type == 2) { //置顶
			foreach(explode(',', $haowu_ids) as $haowu_id) {
				$HaowusDetail = Haowus::where(['user_id'=>$user_id, 'id'=>$haowu_id])->find();
				if($HaowusDetail) {
					if($HaowusDetail['is_top'] == 1) {
						Haowus::where(['user_id'=>$user_id, 'id'=>$haowu_id])->update(['is_top'=>0]);
					} else {
						Haowus::where(['user_id'=>$user_id, 'id'=>$haowu_id])->update(['is_top'=>1]);
					}
				}
			}
		} else {
			$this->success("操作类型错误",[],3);
		}
		$this->success('操作成功');
	}
	
	/**
	 * 好物列表
	 * 
	 * @ApiMethod (POST)
     * @param int user_id   用户id
     * @param int page      当前第几页
     * @param string search 查询    
	 */
	public function haowus_list(){
		$user_id = $this->request->post('user_id');
        $page = $this->request->post('page', 1);
        $count = $this->request->post('count', 10);
		$scenic_name = $this->request->post('scenic_name');
		if( empty($user_id)){
			$this->success("参数错误",[],1);
		}
		//先查询景区ids，然后根据景区id查询景区信息
		$scenic_ids = '';
		$haowuList = Haowus::where(['user_id'=>$user_id, 'delete_time'=>null])->order('is_top desc')->paginate($count, false, ["page" => $page]);
		foreach ($haowuList as &$haowu) {
			$scenic_ids = $scenic_ids.','.$haowu['scenic_id'];
		}
		$scenic_ids = trim($scenic_ids, ',');
        $scenicModel = new Scenic();
        $shopCategroyModel = new ShopCategory();
        if ($this->auth->isLogin()) {
            $shop_id = $this->auth->is_distributor == 1 ? $this->auth->id : $this->auth->shop_id;
        }else{
            $shop_id = 2;
        }
        //景区信息
        $where = [
            'id'  =>  ['in',$scenic_ids],
            'status' => 1,
        ];
        if($scenic_name){
            $where['scenic_name'] = ['like','%'.$scenic_name.'%'];
        }
        //$scenicModel->setShopId($shop_id);
        $field = ['id','scenic_name','scenic_notice','scenic_images','city','address','score','category_id','total_sales'];
        $scenic = $scenicModel->getScenicList($where,$field);
        if ($this->auth->isLogin() && $scenic && $this->auth->is_distributor) {
                switch ($this->auth->level) {
                    case '1':
                        $share_price = 'one_price';
                        break;
                    case '2':
                        $share_price = 'two_price';
                        break;
                    case '3':
                        $share_price = 'three_price';
                        break;
                 }
            $allocationModel = new \app\common\model\DistributionAllocation();
            foreach ($scenic as &$value) {
                $allocation = $allocationModel->field($share_price)->where(['scenic_id'=>$value['id']])->order($share_price.' desc')->find();
                $value['share_price'] = $allocation[$share_price];
				$HaowusDetail = Haowus::where(['user_id'=>$user_id, 'scenic_id'=>$value['id']])->find();
				//好物推荐 用户好物id和置顶状态
				$value['is_top'] = $HaowusDetail['is_top'];
				//$value['haowu_id'] = $HaowusDetail['id'];
				$value['id'] = $HaowusDetail['id'];
				$value['scenic_id'] = $HaowusDetail['scenic_id'];
				//景区商品价格信息
				$salesModel = new \app\store\model\Sales();
				$listSales = $salesModel->field('scenic_id,salePrice,retailPrice')->where(['scenic_id'=>$HaowusDetail['scenic_id'],'sales_status'=>1])->select();
				$listSales = collection($listSales)->toArray();
				$value['prices'] = $listSales;	
            }    
        }else{
            foreach ($scenic as &$value) {
                $allocationModel = new \app\common\model\DistributionAllocation();
                $allocation = $allocationModel
                             ->field('subtract,subtract_money,num_restriction,total_restriction,goods_id')
                             ->where(['scenic_id'=>$value['id'],'subtract'=>2])->order('subtract_money desc')->find();
                $value['subtract_money'] = $allocation['subtract_money'];
                //判断用户是否登录，如果登录，获取当前用户限购商品的订单数量，与限购数量进行比较
                $value['num_restriction']   = $allocation['num_restriction'];
                $value['total_restriction'] = $allocation['total_restriction'];
                $value['discounts_number']  = $allocation['num_restriction'];
                $orderModel = new OrderModel();
                if($this->auth->isLogin() && $allocation && !$this->auth->is_distributor) {
                    $userTicketNum = $orderModel->ticketNumNew($this->auth->id,$allocation['goods_id']);
                    if($allocation['num_restriction'] <= $userTicketNum) {
                        $value['discounts_number'] = 0;
                    }
                }
                //没有限购张数限制
                if($value['num_restriction'] == 0) {
                    $value['discounts_number'] = -1;
                }
				//有总票数限制
                $totalTicketNum = $orderModel->ticketNumNew(0,$allocation['goods_id']);
                if($totalTicketNum >= $value['total_restriction']) {
                    $value['discounts_number'] = 0;
                }
				$HaowusDetail = Haowus::where(['user_id'=>$user_id, 'scenic_id'=>$value['id']])->find();
				//好物推荐 用户好物id和置顶状态
				$value['is_top'] = $HaowusDetail['is_top'];
				//$value['haowu_id'] = $HaowusDetail['id'];
				$value['id'] = $HaowusDetail['id'];
				$value['scenic_id'] = $HaowusDetail['scenic_id'];
				//景区商品价格信息
				$salesModel = new \app\store\model\Sales();
				$listSales = $salesModel->field('scenic_id,salePrice,retailPrice')->where(['scenic_id'=>$HaowusDetail['scenic_id'],'sales_status'=>1])->select();
				$listSales = collection($listSales)->toArray();
				$value['prices'] = $listSales;
            } 
        }
		//置顶排序
		usort($scenic, function($a, $b) {
			return $b['is_top'] - $a['is_top'];
		});
        $data['scenic'] = $scenic;
         //分类标签
        //$data['label'] = $shopCategroyModel->lists($shop_id,$this->auth->store_id,$cate_id);
        if ($this->auth->isLogin()) {
            $data['is_distributor'] = $this->auth->is_distributor;
        }else{
            $data['is_distributor'] = 0;
        }
        
		$this->success('好物推荐列表',$data);
	}
	
    /**
     * [index 分类下的所有关联景区信息]
     * @Author   Ming
     * @DateTime 2024-09-08
     * @return   [type]      [description]
     */
    public function association()
    {
        $cate_id     = $this->request->post('cate_id');    //店铺分类
        $scenic_name = $this->request->post('scenic_name');
        $label_id    = $this->request->post('label_id');  //标签id
        $district    = $this->request->post('district', '370100'); //地区
        $page        = $this->request->post('page',1);
        //if(!$cate_id){
           //$this->error(__('Invalid parameters'));
        //}

        $scenicModel = new Scenic();
        $shopCategroyModel = new ShopCategory();
        if ($this->auth->isLogin()) {
            $shop_id = $this->auth->is_distributor == 1 ? $this->auth->id : $this->auth->shop_id;
        }else{
            $shop_id = 2;
        }
        $scenic_id = $scenicModel->getDistributorScenic($shop_id);

        //景区信息
        $where = [
            'id'  =>  ['in',$scenic_id],
            'status' => 1,
        ];
        if($cate_id){
        	$where['scenic_type'] = $cate_id; //店铺分类
        }
        if($scenic_name){
            $where['scenic_name'] = ['like','%'.$scenic_name.'%'];
        }

        if($label_id){
            $where['sceniclabel'] = $label_id;
        }

        if (is_numeric($district)) {
            $where['city_id'] = $district;
        } else {
            $where['city'] = ['like', '%' . $district . '%'];
        }
        
        $scenicModel->setShopId($shop_id);
        $field = ['id','scenic_name','scenic_notice','scenic_images','city','address','total_sales','score','category_id'];
        $scenic = $scenicModel->getScenicListCount($where,$field,$page);
        if ($this->auth->isLogin() && $scenic && $this->auth->is_distributor) {
                switch ($this->auth->level) {
                    case '1':
                        $share_price = 'one_price';
                        break;
                    case '2':
                        $share_price = 'two_price';
                        break;
                    case '3':
                        $share_price = 'three_price';
                        break;
                 }
            $allocationModel = new \app\common\model\DistributionAllocation();
            foreach ($scenic as &$value) {
                $allocation = $allocationModel->field($share_price)->where(['scenic_id'=>$value['id']])->order($share_price.' desc')->find();
                $value['share_price'] = $allocation[$share_price];
				//景区商品价格信息
				$salesModel = new \app\store\model\Sales();
				$listSales = $salesModel->field('scenic_id,salePrice,retailPrice')->where(['scenic_id'=>$value['id'],'sales_status'=>1])->select();
				$listSales = collection($listSales)->toArray();
				$value['prices'] = $listSales;					
            }		
        }else{
            foreach ($scenic as &$value) {
                $allocationModel = new \app\common\model\DistributionAllocation();
                $allocation = $allocationModel
                             ->field('subtract,subtract_money,num_restriction,total_restriction,goods_id')
                             ->where(['scenic_id'=>$value['id'],'subtract'=>2])->order('subtract_money desc')->find();
                $value['subtract_money'] = $allocation['subtract_money'];
                //判断用户是否登录，如果登录，获取当前用户限购商品的订单数量，与限购数量进行比较
                $value['num_restriction']   = $allocation['num_restriction'];
                $value['total_restriction'] = $allocation['total_restriction'];
                $value['discounts_number']  = $allocation['num_restriction'];
                $orderModel = new OrderModel();
                if($this->auth->isLogin() && $allocation && !$this->auth->is_distributor) {
                    $userTicketNum = $orderModel->ticketNumNew($this->auth->id,$allocation['goods_id']);
                    if($allocation['num_restriction'] <= $userTicketNum) {
                        $value['discounts_number'] = 0;
                    }
                }
                //没有限购张数限制
                if($value['num_restriction'] == 0) {
                    $value['discounts_number'] = -1;
                }
				//有总票数限制
                $totalTicketNum = $orderModel->ticketNumNew(0,$allocation['goods_id']);
                if($totalTicketNum >= $value['total_restriction']) {
                    $value['discounts_number'] = 0;
                }
				//景区商品价格信息
				$salesModel = new \app\store\model\Sales();
				$listSales = $salesModel->field('scenic_id,salePrice,retailPrice')->where(['scenic_id'=>$value['id'],'sales_status'=>1])->select();
				$listSales = collection($listSales)->toArray();
				$value['prices'] = $listSales;
            } 
        }
        $data['scenic'] = $scenic;
         //分类标签
        if($cate_id){
            $data['label'] = $shopCategroyModel->lists($shop_id, 2, $cate_id);
        }
        if ($this->auth->isLogin()) {
            $data['is_distributor'] = $this->auth->is_distributor;
        }else{
            $data['is_distributor'] = 0;
        }
        
       $this->success('关联商品信息',$data);
    }
	
    /**
     * [获取分类信息]
     * @Author   Ming
     * @DateTime 2024-09-08
     * @return   
     */
    public function get_category()
    {
		$shop_id = 2;
		$store_id = 2;
		$shopCateModel = new ShopCategory();
		$category = $shopCateModel->lists($shop_id,$store_id);
		$this->success('分类信息',$category);
	}
	
	
	
    /**
     * [动态关联多个景区信息]
     * @Author   Ming
     * @DateTime 2024-09-12
     * @return   [type]      [description]
     */
    public function associated_scenics()
    {
        $scenic_ids = $this->request->post('scenic_ids');    //多个景区id  id1,id2,id3
        if(!$scenic_ids){
           $this->error(__('Invalid parameters'));
        }

        $scenicModel = new Scenic();
        $shopCategroyModel = new ShopCategory();
        if ($this->auth->isLogin()) {
            $shop_id = $this->auth->is_distributor == 1 ? $this->auth->id : $this->auth->shop_id;
        }else{
            $shop_id = 2;
        }

        //景区信息
        $where = [
            'id'  =>  ['in',$scenic_ids],
            'status' => 1,
        ];

        $scenicModel->setShopId($shop_id);
        $field = ['id','scenic_name','scenic_notice','scenic_images','city','address','total_sales','score','category_id'];
        //$scenic = $scenicModel->getScenicList($where,$field,$page);
        $scenic = $scenicModel->getScenicList($where,$field);
        if ($this->auth->isLogin() && $scenic && $this->auth->is_distributor) {
                switch ($this->auth->level) {
                    case '1':
                        $share_price = 'one_price';
                        break;
                    case '2':
                        $share_price = 'two_price';
                        break;
                    case '3':
                        $share_price = 'three_price';
                        break;
                 }
            $allocationModel = new \app\common\model\DistributionAllocation();
            foreach ($scenic as &$value) {
                $allocation = $allocationModel->field($share_price)->where(['scenic_id'=>$value['id']])->order($share_price.' desc')->find();
                $value['share_price'] = $allocation[$share_price];
				//景区商品价格信息
				$salesModel = new \app\store\model\Sales();
				$listSales = $salesModel->field('scenic_id,salePrice,retailPrice')->where(['scenic_id'=>$value['id'],'sales_status'=>1])->select();
				$listSales = collection($listSales)->toArray();
				$value['prices'] = $listSales;					
            }		
        }else{
            foreach ($scenic as &$value) {
                $allocationModel = new \app\common\model\DistributionAllocation();
                $allocation = $allocationModel
                             ->field('subtract,subtract_money,num_restriction,total_restriction,goods_id')
                             ->where(['scenic_id'=>$value['id'],'subtract'=>2])->order('subtract_money desc')->find();
                $value['subtract_money'] = $allocation['subtract_money'];
                //判断用户是否登录，如果登录，获取当前用户限购商品的订单数量，与限购数量进行比较
                $value['num_restriction']   = $allocation['num_restriction'];
                $value['total_restriction'] = $allocation['total_restriction'];
                $value['discounts_number']  = $allocation['num_restriction'];
                $orderModel = new OrderModel();
                if($this->auth->isLogin() && $allocation && !$this->auth->is_distributor) {
                    $userTicketNum = $orderModel->ticketNumNew($this->auth->id,$allocation['goods_id']);
                    if($allocation['num_restriction'] <= $userTicketNum) {
                        $value['discounts_number'] = 0;
                    }
                }
                //没有限购张数限制
                if($value['num_restriction'] == 0) {
                    $value['discounts_number'] = -1;
                }
				//有总票数限制
                $totalTicketNum = $orderModel->ticketNumNew(0,$allocation['goods_id']);
                if($totalTicketNum >= $value['total_restriction']) {
                    $value['discounts_number'] = 0;
                }
				//景区商品价格信息
				$salesModel = new \app\store\model\Sales();
				$listSales = $salesModel->field('scenic_id,salePrice,retailPrice')->where(['scenic_id'=>$value['id'],'sales_status'=>1])->select();
				$listSales = collection($listSales)->toArray();
				$value['prices'] = $listSales;
            } 
        }
        $data['scenic'] = $scenic;
         //分类标签
        //$data['label'] = $shopCategroyModel->lists($shop_id, 2, $cate_id);
        if ($this->auth->isLogin()) {
            $data['is_distributor'] = $this->auth->is_distributor;
        }else{
            $data['is_distributor'] = 0;
        }
        
       $this->success('动态关联多个景区信息', $data);
    }
    

	/**
	 * 修改shop_id
     * 
	 * @ApiMethod (POST)
	 */
	public function modifyShopId()
	{
	    $shop_id  = $this->request->request('userId');
	    if(!$shop_id){
           $this->error(__('Invalid parameters'));
        }
        
        $userModel = new \app\common\model\User();
        if ($this->auth->isLogin()) {
            $tmpUser = $userModel->where(['id'=>$shop_id])->find();
            if(!$tmpUser) {
                $this->success("用户不存在",[],2);
            }
            if ($tmpUser->is_distributor && $shop_id && !$this->auth->is_distributor && $shop_id != $this->auth->shop_id) {
            //if ($shop_id && !$this->auth->is_distributor && $shop_id != $this->auth->shop_id) {
				$user      = $userModel->where(['id'=>$this->auth->id])->find();
				$user->shop_id = $shop_id;
				$user->save();
				$this->success('用户信息更新成功',$user);
            }else {
                $this->success('用户信息无需更新');
            }
        }else {
            $this->error('用户未登录');
        }
	}
}
